﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TV4Home.Server.TVEInteractionLibrary;
using TV4Home.Server.TVEInteractionLibrary.Interfaces;
using TV4Home.WebInterface.UI.Code;

namespace TV4Home.WebInterface.UI.Controls
{
    public partial class TVGuideSingleRowControl : System.Web.UI.UserControl
    {
        public int ChannelID { get; set; }
        public DateTime StartTime { get; set; }
        public DateTime EndTime { get; set; }
        public event EventHandler<ChannelClickedEventArgs> ChannelClicked;

        protected void Page_Load(object sender, EventArgs e)
        {
        }

        public void LoadData()
        {
            ShowGuideForChannel(WebService.TV4HomeWebService.ServiceInstance.GetProgramsBasicForChannel(ChannelID, this.StartTime, this.EndTime).ToList());
        }

        private void ShowGuideForChannel(List<WebProgramBasic> programs)
        {
            AddChannelNameAndLogo();

            FixEPGHoles(programs);

            AddProgramsToRow(programsPanel, programs);
        }

        private void FixEPGHoles(List<WebProgramBasic> programs)
        {
            if (programs.Count == 0)
                programs.Add(GetNoEPGProgram(this.StartTime, this.EndTime));
            else
            {
                WebProgramBasic first = programs[0];

                if (first.StartTime > this.StartTime)
                    programs.Insert(0, GetNoEPGProgram(this.StartTime, first.StartTime));

                for (int i = 0; i < programs.Count - 1; i++)
                {
                    WebProgramBasic current = programs[i];

                    WebProgramBasic next = programs[i + 1];

                    if (current.EndTime != next.StartTime)
                    {
                        programs.Insert(i + 1, GetNoEPGProgram(current.EndTime, next.StartTime));
                        i--; //do current item again
                    }
                }

                WebProgramBasic last = programs[programs.Count - 1];

                if (last.EndTime < this.EndTime)
                    programs.Add(GetNoEPGProgram(last.EndTime, this.EndTime));
            }
        }

        private WebProgramBasic GetNoEPGProgram(DateTime startTime, DateTime endTime)
        {
            return new WebProgramBasic()
                       {
                           IdProgram = 0,
                           IdChannel = ChannelID,
                           StartTime = startTime,
                           EndTime = endTime,
                           Title = TV4Home.WebInterface.UI.Properties.Resources.TVGuide_NoEPGAvailable,
                           Description = "",
                           DurationInMinutes = (endTime - startTime).Minutes
                       };
        }

        private void AddChannelNameAndLogo()
        {
            WebChannelBasic channel = WebService.TV4HomeWebService.ServiceInstance.GetChannelBasicById(ChannelID);

            this.imgChannelLogo.ImageUrl = Utils.GetChannelLogoPath(channel);
            this.lblChannelName.Text = channel.DisplayName;

            this.LinkButtonChannelDetails.CommandArgument = channel.IdChannel.ToString();

            if (System.IO.File.Exists(MapPath(this.imgChannelLogo.ImageUrl)))
            {
                this.imgChannelLogo.Visible = true;

                if (WebsiteSettings.ShowChannelNameIfChannelPictureIsPresent)
                {
                    this.lblChannelName.Visible = true;
                    this.lblChannelName.Style.Add("margin-top", "-2px");
                    this.imgChannelLogo.CssClass = "TVGuideCellChannelImageWithChannelText";
                }
                else
                {
                    this.lblChannelName.Visible = false;
                    this.imgChannelLogo.CssClass = "TVGuideCellChannelImageWithoutChannelText";
                }
            }
        }

        private void AddProgramsToRow(Panel row, List<WebProgramBasic> programs)
        {
            foreach (WebProgramBasic program in programs)
            {
                Panel singleProgramPanel = new Panel();

                singleProgramPanel.Attributes.Add("programID", program.IdProgram.ToString());

                bool shouldAdd = AddProgramToPanel(singleProgramPanel, program);

                if (shouldAdd)
                    row.Controls.Add(singleProgramPanel);
            }
        }

        private bool AddProgramToPanel(Panel singleProgramPanel, WebProgramBasic program)
        {
            double totalDuration = (this.EndTime - this.StartTime).TotalMinutes;

            if (program.IsScheduled)
                singleProgramPanel.CssClass = "TVGuideCellProgramOnScheduled";
            else if (program.StartTime <= DateTime.Now && program.EndTime >= DateTime.Now)
                singleProgramPanel.CssClass = "TVGuideCellProgramOnAir";
            else
                singleProgramPanel.CssClass = "TVGuideCellProgram";

            double percentage;

            if (program.StartTime <= this.StartTime)
                percentage = 100.0 / totalDuration * (program.EndTime - this.StartTime).TotalMinutes;
            else if (program.EndTime <= this.EndTime)
                percentage = 100.0 / totalDuration * (program.EndTime - program.StartTime).TotalMinutes;
            else
            {
                double width = (this.EndTime - program.StartTime).TotalMinutes;
                percentage = 100.0 / totalDuration * (width < 0 ? 0 : width);
            }

            if (percentage > 100)
                percentage = 100;

            if (percentage < 0)
                percentage = 0;

            singleProgramPanel.Width = Unit.Percentage(percentage * 0.99);

            if (singleProgramPanel.Width.Value > 0)
            {
                if (program.IdProgram != 0)
                {
                    HyperLink descrText = new HyperLink() { Text = @"&nbsp;" + program.Title, CssClass = "TVGuideCellProgramText" };

                    descrText.NavigateUrl = "~/ProgramInfoDialog.aspx?id=" + program.IdProgram;
                    descrText.Attributes.Add("onClick", String.Format("showProgramInfoDialog('{0}'); return false;", program.IdProgram));

                    singleProgramPanel.ID = "program" + program.IdProgram;

                    // add seperators
                    singleProgramPanel.Controls.Add(new Panel() { CssClass = "TVGuideCellProgramLeftSeperator" });
                    singleProgramPanel.Controls.Add(new Panel() { CssClass = "TVGuideCellProgramRightSeperator" });

                    singleProgramPanel.Controls.Add(descrText);
                }
                else  // no EPG
                {
                    singleProgramPanel.CssClass = "TVGuideCellProgramNoEPG";
                    Label descrText = new Label() { Text = program.Title, CssClass = "TVGuideCellProgramTextNoEPG" };

                    singleProgramPanel.Controls.Add(descrText);
                }

                return true;
            }

            return false;
        }

        protected void LinkButtonChannelDetails_Command(object sender, CommandEventArgs e)
        {
            if (ChannelClicked != null)
                ChannelClicked.Invoke(this, new ChannelClickedEventArgs(Convert.ToInt32(e.CommandArgument)));
        }
    }
}